<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>资讯管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="formInline.kw"
          placeholder="输入关键字"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表 informationId type location floor tags status-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" prop="title" label="资讯标题" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="publisher" label="发布人" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.publisher.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="tags" label="标签">
        <template slot-scope="scope" v-if="scope.row.tags!=null">
          <el-tag size="small" type="warning" v-for="(tag,id) in scope.row.tags.split(';')" :key="id">{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="publishTime" label="发布时间" width="220">
        <template slot-scope="scope">
          <div>{{scope.row.publishTime|timestampToDayHM}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleDetail(scope.$index, scope.row)" icon="el-icon-document">详情</el-button>
          <el-button
            v-if="scope.row.publisher.adminId==loginAdmin.adminId"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope.$index, scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="danger" @click="offShelf(scope.$index, scope.row, -1)" icon="el-icon-close" v-if="scope.row.publisher.adminId==loginAdmin.adminId">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="70%"
      :close-on-click-modal=false
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="资讯标题" prop="title">
          <el-input
            size="small"
            v-model="editForm.title"
            auto-complete="off"
            placeholder=""
          ></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input
            size="small"
            v-model="editForm.tags"
            auto-complete="off"
            placeholder="如：健康知识、手机使用技巧"
          ></el-input>
        </el-form-item>
        <el-form-item label="正文内容" prop="content" id='quillEditorQiniu'>
          <!-- 基于elementUi的上传组件 el-upload-->
          <el-upload
              class="avatar-uploader"
              :action="uploadImgUrl"
              :accept="'image/*'"
              :show-file-list="false"
              :on-success="uploadEditorSuccess"
              :on-error="uploadEditorError"
              :before-upload="beforeEditorUpload">
          </el-upload>
          <quill-editor  class="editor"  v-model="editForm.content" ref="customQuillEditor" :options="editorOption" >
          </quill-editor>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio v-model="editForm.status" :label="1">正常</el-radio>
          <el-radio v-model="editForm.status" :label="2">维修中</el-radio>
        </el-form-item> -->
        <el-form-item label="图片" prop="role">
          <el-upload 
            class="avatar-uploader showUploader"
            ref="businessLicense"
            action
            multiple
            :auto-upload="false"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-change="uploadSectionFile"
            :limit="3"
          >
            <ul class="img-list">
              <li v-for="pic in photos" :key="pic" class="img-li">
                <img :src="pic" class="avatar" />
              </li>
              <li v-if="photos.length==0 || photos.length<4" class="el-icon-plus avatar-uploader-icon"></li>
            </ul>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          v-loading.fullscreen.lock="fullscreenLoading"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!--详情对话框-->
    <el-dialog
      title="资讯信息详情"
      :visible.sync="contentVisible"
      width="60%"
      :close-on-click-modal=false
      @click="closeDialog2"
    >
    <el-descriptions class="margin-top" :column="1" border v-if="currDetailData!=null">
        <el-descriptions-item label="资讯标题">{{ currDetailData.title }}</el-descriptions-item>
        <el-descriptions-item label="标签" v-if="currDetailData.tags!=null">
          <el-tag size="small" type="warning" v-for="(tag,id) in currDetailData.tags.split(';')" :key="id">{{ tag }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布人">{{ currDetailData.publisher.realName }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{currDetailData.publishTime|timestampToDayHM}}</el-descriptions-item>
    </el-descriptions>
    <div class="dtitle">正文内容：</div>
    <div v-html="currDetailData.content" class="introduction" v-if="currDetailData!=null"></div>
    <!-- <div class="dtitle">附图：</div>
    <div class="demo-image">
      <div class="block" v-for="fit in currDetailheadPic" :key="fit">
        <el-image
          style="width: 100px; height: 100px"
          :src="fit"
          fit="cover"></el-image>
      </div>
    </div> -->
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination.vue";
import axios from 'axios';
import * as Quill from 'quill'
import { GetInfoList, SaveInfo, DeleteInfo } from '@/api/api.js'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons

  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'direction': 'rtl'}],                         // text direction

  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],

  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  [{'font': []}],
  [{'align': []}],
  ['link', 'image'],
  ['clean']                                         // remove formatting button
];

export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      contentVisible: false, //详情对话框显示与隐藏
      title: "添加资讯",
      editForm: {
        title: "",
        tags: "",
        headPic: "",
        content: "",
      },
      files: {},
      photos: [],
      // rules表单验证
      rules: {
        type: [{ required: true, message: "请输入", trigger: "blur" }],
        title: [{ required: true, message: "请输入", trigger: "blur" }],
        tags: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      formInline: {
        kw: "",
        currentPage: 1,
        pageSize: 10,
      },
      listData: [], //列表数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
      currDetailData: null,
      currDetailheadPic: [],
      uploadImgUrl:"/care-server/admin/uploadPic",
      uploadUrlPath:"没有文件上传",
      quillUpdateImg:false,
      editorOption:{
        placeholder:'请输入正文',
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('#quillEditorQiniu .avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              },
            }
          }
        }
      },
      fullscreenLoading: false,
      loginAdmin: null
    };
  },
  // 注册组件
  components: {
    Pagination,
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
    this.loginAdmin = JSON.parse(localStorage.getItem('LoginAdmin'))
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取资讯列表
    getdata(parameter) {
      this.loading = true;
      GetInfoList(parameter)
        .then((res) => {
          this.loading = false;
          if (res.success) {
            this.listData = res.data.records;
            this.pageparm.currentPage = res.data.currentPage;
            this.pageparm.pageSize = res.data.pageSize;
            this.pageparm.total = res.data.totalrecord;
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch((err) => {
          this.editFormVisible = false;
          this.loading = false;
          this.$message.error("获取数据失败，请稍后再试！");
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.currentPage = parm.currentPage;
      this.formInline.pageSize = parm.pageSize;
      this.formInline.total = parm.total
      this.getdata(this.formInline);
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline);
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改资讯信息";
        this.editForm.informationId = row.informationId
        this.editForm.title = row.title
        this.editForm.tags = row.tags
        this.editForm.headPic = row.headPic
        this.editForm.content = row.content
        this.photos=row.headPic.split(",")
      } else {
        this.title = "添加资讯";
        this.editForm.informationId = null
        this.editForm.title = ""
        this.editForm.tags = ""
        this.editForm.headPic = ""
        this.editForm.content = ""
        this.photos=[]
        this.currDetailheadPic = []
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          this.fullscreenLoading = true
          console.log('保存资讯：', this.editForm)
          SaveInfo(this.editForm)
            .then((res) => {
              this.editFormVisible = false
              this.fullscreenLoading = false
              this.loading = false;
              if (res.success) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "保存成功！",
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
              this.files = {}
              this.photos=[]
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },
    // 删除
    offShelf(index, row, status) {
      let msg = "确定要删除该资讯吗？"
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          DeleteInfo({infoId: row.informationId})
            .then((res) => {
              if (res.success) {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("操作失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //显示详情界面
    handleDetail: function (index, row) {
      this.contentVisible = true
      this.currDetailData = row
      this.currDetailheadPic = row.headPic.split(",")
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
    },
    closeDialog2() {
      this.contentVisible = false;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    uploadSectionFile(file) {
      console.log('选定图片！')
      const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
      const isJPG = typeArr.indexOf(file.raw.type) !== -1;
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        this.$message.error("只能是图片!");
        this.$refs.upload.clearFiles();
        this.files = null;
        return;
      }
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        this.$refs.upload.clearFiles();
        this.files = null;
        return;
      }
      this.files = file.raw;
      // FormData 对象
      var formData = new FormData();
      // 文件对象
      formData.append("file", this.files);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        methods: "post",
      };
      axios.post("http://localhost:9081/care-server/admin/uploadPic", formData, config).then((res) => {
        if (res.data.success) {
          console.log('图片上传成功！', res.data)
          this.photos.push(res.data.data);
          if(this.editForm.headPic!=""){
            this.editForm.headPic = this.editForm.headPic+","+res.data.data
          }else{
            this.editForm.headPic = res.data.data
          }
          console.log(this.editForm.headPic)
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 上传图片成功
    uploadEditorSuccess(res, file) {
      console.log("上传成功")
      // this.$emit('upload',res, file)
      console.log(res, file);
      //拼接出上传的图片在服务器的完整地址
      let imgUrl=res.data;
      let type=imgUrl.substring(imgUrl.lastIndexOf(".")+1);
      console.log(type);
      // 获取富文本组件实例
      let quill = this.$refs.customQuillEditor.quill;
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片 res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', imgUrl)
      // 调整光标到最后
      quill.setSelection(length + 1)
      //取消上传动画
      this.quillUpdateImg = false;
    },
    // 上传(文件)图片失败
    uploadEditorError(res, file) {
      console.log(res);
      console.log(file);
      //页面提示
      this.$message.error('上传图片失败')
      //取消上传动画
      this.quillUpdateImg = false;
    },
    //上传图片之前async
    beforeEditorUpload(res, file){
      //显示上传动画
      this.quillUpdateImg = true;
      //  const res1 = await uploadImage()
      // console.log(res1,'=====');
      // this.$emit('before',res, file)
      console.log(res);
      console.log(file);
    },
    //上传组件返回的结果
    uploadResult:function (res){
      this.uploadUrlPath=res;
    },
  },
};
</script>

<style>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.avatar-uploader /deep/ .el-upload {
    border-radius: 6px;
    background-color: #fff;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #c33534;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    border: 1px dashed #8c939d;
    width: 180px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }
  .showUploader /deep/ .el-upload-list{
    display: none;
  }
  .avatar {
    width: 100%;
    height: 140px;
    display: block;
  }
  .img-list{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
  }
  .img-list .img-li{
    display: inline-block;
    margin-right: 1%;
    width: 180px;
    margin-bottom: 5px;
  }
  .demo-image{
    margin-top: 15px;
  }
  .quill-editor {
    height: 250px;
    margin-bottom: 100px;
  }
  .dtitle{
    font-size: 16px;
    margin: 10px 0;
    color: #666;
  }
  .introduction{
    margin: 15px 0;
  }
  div.el-upload{
    width: 100%;
  }
</style>

 
 